package praktikum_2_ylesanded.ylesanne_1;

/**
 * Created by IntelliJ IDEA.
 * User: Jaan Sepp and Martti Elias
 * Date: 2.10.11
 * Time: 12:09
 */
public class DynamicArray {
  int[] dynamicArray;

  int currentIndex;

  public DynamicArray() {
    dynamicArray = new int[1];
    currentIndex = 0;
  }

  public int[] getDynamicArray() {
    return dynamicArray;
  }

  public void add(int number) {
    dynamicArray[currentIndex] = number;
    currentIndex++;
    if (dynamicArray.length == currentIndex) doubleDynamicArraySize();
  }

  public void addAll(int[] numbersToAdd) {
    for (int number : numbersToAdd) {
      this.add(number);
    }
  }

  public int rem() {
    int lastNumber = dynamicArray[currentIndex - 1];
    dynamicArray[currentIndex - 1] = 0;
    currentIndex--;
    if (currentIndex - 1 < dynamicArray.length / 4) decreaseDynamicArraySize();
    return lastNumber;
  }

  public int get(int index) {
    try {
      return dynamicArray[index];
    } catch (IndexOutOfBoundsException e) {
      System.out.println("WARNING: Index is out of the bounds of the dynamic array!");
      return -1;
    }
  }

  public void put(int number, int index) {
    if (index < currentIndex && index >= 0) {
      dynamicArray[index] = number;
    } else {
      System.out.println("WARNING: Index is out of the bounds of the dynamic array!");
    }
  }

  public int len() {
    return currentIndex;
  }

  private void doubleDynamicArraySize() {
    makeNewArrayWithOldInfo((len()) * 2);
  }

  private void decreaseDynamicArraySize() {
    makeNewArrayWithOldInfo(dynamicArray.length / 2);
  }

  private void makeNewArrayWithOldInfo(int size) {
    int[] tempArray = dynamicArray;
    dynamicArray = new int[size];
    System.arraycopy(tempArray, 0, dynamicArray, 0, currentIndex);
  }
}
